package com.example.mydemo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.pad.lib_camera.api.CameraAttributes;
import com.pad.lib_camera.api.CameraEvents;
import com.pad.lib_camera.basic.CameraEngine;
import com.pad.lib_camera.type.CameraFacing;
import com.pad.lib_camera.type.CameraOutputFormat;
import com.pad.lib_camera.type.CameraSize;
import com.tal.pad.eye_protection.AwConDetectApi;
import com.tal.pad.eye_protection.ResultInfo;
import com.tal.pad.eye_protection.interfaces.NoPersonStatusCallback;
import com.tal.pad.eye_protection.interfaces.ProtectEyeResultCallback;

import java.util.ArrayList;
import java.util.List;

public class CameraTestActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    private CameraEngine cameraEngine;
    private static final int PERMISSION_REQUEST_CODE = 1;
    private int previewWidth = 0;
    private int previewHeight = 0;
    private static final int MSG_STAR = 101;
    private static final int MSG_STOP = 102;
    private static final int MSG_SET_RESULT = 103;
    private static final int MSG_LOG = 104;
    private static final long TIME_WORK = 15000; // 数据采集时间 毫秒
    private static final long TIME_SLLEP = 20000; // 相机休眠时间 毫秒
    private SurfaceHolder holder;
    private String logStr = "";
    private TextView tv_result;
    private TextView tv_log;
    private SurfaceView surfaceView01;
    private StringBuffer stringBuffer =new StringBuffer();

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_STAR:
                    cameraEngine.startPreview(holder.getSurface(), CameraFacing.FRONT);
                    sendEmptyMessageDelayed(MSG_STOP, TIME_WORK);
                    break;
                case MSG_STOP:
                    AwConDetectApi.getInstance().getResult(new ProtectEyeResultCallback() {
                        @Override
                        public void onResult(ResultInfo resultInfo) {
                            Message msg0 = Message.obtain();
                            msg0.what = MSG_SET_RESULT;
                            msg0.obj = resultInfo;
                            sendMessage(msg0);
                        }
                    });
                    cameraEngine.stopPreview();
                    sendEmptyMessageDelayed(MSG_STAR, TIME_SLLEP);
                    break;
                case MSG_SET_RESULT:
                    ResultInfo reBean = (ResultInfo) msg.obj;
                    String str = "趴着次数:" + reBean.prostrate_time + " 打哈欠次数:" + reBean.yawn_count +
                            " 瞌睡次数:" + reBean.sleep_time + " 低头次数:" + reBean.headdown_time +
                            " 俯视次数:" + reBean.lookdown_time + " 仰头次数:" + reBean.headup_time +
                            " 抬头次数:" + reBean.lookup_time + " 歪头次数:" + reBean.headtilt +
                            " 侧脸次数:" + reBean.faceprofile + " 东张西望次数:" + reBean.lookaround +
                            " 斜肩次数:" + reBean.shouldertilt;
                    tv_result.setText("结果：\n" + str);
//                    Date currentDate = new Date();
//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
//                    String formattedDate = dateFormat.format(currentDate);
//                    stringBuffer.append("\n"+formattedDate+"\n"+str);
//                    tv_log.setText(stringBuffer);
                    break;
                case MSG_LOG:
                    logStr += msg.obj;
                    tv_log.setText(logStr);
                    Message msg1 = Message.obtain();
                    msg1.what = MSG_LOG;
                    msg1.obj = "msg\n";
                    sendMessageDelayed(msg1, 500);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_test);
        tv_result=findViewById(R.id.tv_result);
        tv_log=findViewById(R.id.tv_log);
        surfaceView01=findViewById(R.id.surfaceView01);
        surfaceView01.getHolder().addCallback(this);
        checkAndRequestPermissions();
        cameraEngine = new CameraEngine(new CameraEvents() {
            @Override
            public void onPreviewStarted(boolean b, @NonNull CameraSize cameraSize) {
                previewWidth = cameraSize.getWidth();
                previewHeight = cameraSize.getHeight();
            }

            @Override
            public void onDataFrame(@NonNull CameraOutputFormat cameraOutputFormat, boolean flip, boolean isFront, @NonNull byte[] data) {
                AwConDetectApi.getInstance().detectFrame(data, previewWidth, previewHeight, 0, 0, 0, "traceId");
            }

            @Override
            public void onPreviewStopped() {

            }

            @Override
            public void onCameraOpened(@NonNull CameraAttributes cameraAttributes) {

            }

            @Override
            public void onCameraError(@NonNull String s) {

            }

            @Override
            public void onCameraClosed() {

            }


        }, this);
        cameraEngine.setFlipHorizontal(true);
        cameraEngine.setOutputFormat(CameraOutputFormat.YUV_420);
        cameraEngine.setDataFrameInterval(300);
        cameraEngine.setPhotoSize(new CameraSize(640, 480));

    }
    private void checkAndRequestPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();


        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.CAMERA);
        }


        // 如果有需要请求的权限，则发起请求
        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    permissionsToRequest.toArray(new String[0]),
                    PERMISSION_REQUEST_CODE);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            if (allPermissionsGranted) {
                Toast.makeText(this, "所有权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "部分权限未授予", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        this.holder = holder;
        Message message = Message.obtain();
        message.what = MSG_STAR;
        handler.handleMessage(message);
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        cameraEngine.stopPreview();
    }
    public void getResult(View view) {
        AwConDetectApi.getInstance().getResult(resultInfo -> {

            handler.post(() -> tv_result.setText("结果：" + new Gson().toJson(resultInfo)));
        });
    }
    public void resetResult(View view) {
        tv_result.setText("");
        AwConDetectApi.getInstance().resetResult();
    }

    public void clearLog(View view) {
        logStr = "";
        stringBuffer.setLength(0);
        tv_log.setText(logStr);
    }
    public void getNoPersonStatus(View view){
        AwConDetectApi.getInstance().getNoPersonStatus(new NoPersonStatusCallback() {
            @Override
            public void onNoPersonStatus(int status) {
                Log.e("+++", "onNoPersonStatus: "+status );
            }
        });
    }
}